#include<iostream>
#include<vector>
#include<stack>

using namespace std;

vector<int> solve(vector<int>& a) {
    int n = a.size();
    vector<int> after(n + 1);
    for (int i = n - 1; i >= 0; i--)
        after[i] = max(after[i + 1], a[i]);
    stack<int> s;

    int i = 0;
    vector<int> res;
    while (i < n || s.size())
    {
        if (s.size() && (i >= n || s.top() >= after[i]))
        {
            res.push_back(s.top());
            s.pop();
        }
        else {
            s.push(a[i]);
            i++;
        }
    }

    return res;
}